/**
 * Copyright 2010  Pavel Nemec <nemecp4@gmail.com> <br>
 * <br>
 * License - GPLv3<br>
 *<br>
 * This program is free software; you can redistribute it and/or modify<br>
 * it under the terms of the GNU General Public License as published by<br>
 * the Free Software Foundation; either version 3 of the License, or<br>
 * (at your option) any later version.<br>
 *<br>
 * This program is distributed in the hope that it will be useful,<br>
 * but WITHOUT ANY WARRANTY; without even the implied warranty of<br>
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>
 * GNU General Public License for more details.<br>
 *<br>
 * You should have received a copy of the GNU General Public License<br>
 * along with this program. If not, see <http://www.gnu.org/licenses/>.<br>
 *<br>
 */
package eu.whowie.jast.server;

import java.util.logging.Logger;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

import eu.whowie.jast.remote.UIRemoteInterface;
import eu.whowie.jast.server.web.ApplicationContext;

/**
 * wiring WEB server starter together
 * 
 * @author Pavel Nemec
 * 
 */
public class Main {

	private final Logger logger = Logger.getLogger("JAST_SERVER");

	private JastRmiServer jastRmiServer;

	private Server server;

	private int PORT = 8080;

	private ApplicationContext context;

	public Main() {
		this.context = ApplicationContext.getContext();
		startMockup();
		startRmiServer();
		context.setRmiSErver(jastRmiServer);
		startWebServer();

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("hello world");
		Main m = new Main();

		m.stopRmiServer();

	}

	private void startMockup() {
		ServerSideClientMockup mockup = new ServerSideClientMockup(
				"Server side mockup", ApplicationContext.getContext());
		mockup.show();

	}

	private void startRmiServer() {

		logger.info("starting RMI server");
		jastRmiServer = new JastRmiServer();
		jastRmiServer.start();
		jastRmiServer.export((UIRemoteInterface) context, "JYUI");
	}

	private void startWebServer() {
		try {
			server = new Server();
			final Connector connector = new SelectChannelConnector();
			connector.setPort(PORT);
			server.setConnectors(new Connector[] { connector });

			WebAppContext webappcontext = new WebAppContext();
			webappcontext.setContextPath("");
			webappcontext.setWar("cfg/WebContent");
			webappcontext.setClassLoader(Thread.currentThread()
					.getContextClassLoader());

			server.setHandler(webappcontext);

			server.start();

			server.join();

			logger.info("Jetty started, please go to http://localhost:" + PORT
					+ "/");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void stopRmiServer() {
		logger.info("stoping RMI server");
		jastRmiServer.stop();

	}
}
